package com.yunche.yunchebusiness.ui.activity.system

import com.alibaba.fastjson.JSONObject
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.api.Api
import com.yunche.yunchebusiness.base.BaseActivity
import com.yunche.yunchebusiness.base.rx.SchedulerUtils
import com.yunche.yunchebusiness.common.CommonDialog
import com.yunche.yunchebusiness.common.Constant
import com.yunche.yunchebusiness.entity.AreaEntity
import com.yunche.yunchebusiness.entity.BaseArea
import com.yunche.yunchebusiness.entity.TenantInfoEntity
import com.yunche.yunchebusiness.network.RequestJson
import com.yunche.yunchebusiness.network.RetrofitManager
import com.yunche.yunchebusiness.network.exception.ErrorStatus
import com.yunche.yunchebusiness.network.exception.ExceptionHandle
import com.yunche.yunchebusiness.utils.ToastyUtils
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_change_address.*
import okhttp3.RequestBody

class ChangeAddressActivity : BaseActivity() {
    private var tenantEntity: TenantInfoEntity? = null
    private var areaEntity = listOf<AreaEntity>()
    override fun setLayout(): Int = R.layout.activity_change_address
    private var compositeDisposable = CompositeDisposable()
    private var provinceName = ""
    private var areaName = ""
    private var provinceId = 0L
    private var areaId = 0L

    override fun initView() {

    }

    override fun initData() {
        tenantEntity = intent.extras.getSerializable("tenant") as TenantInfoEntity
        if (tenantEntity != null) {

            provinceId = tenantEntity!!.tenant.parentAreaId
            areaId = tenantEntity!!.tenant.areaId

            areaName = tenantEntity!!.tenant.areaName
            provinceName = tenantEntity!!.tenant.parentAreaName
            tv_tenant_address.text = provinceName + areaName
            et_address_info.setText(tenantEntity!!.tenant.address)

        }
    }

    override fun initEvent() {
        linlay_area.setOnClickListener {
            if (areaEntity.isEmpty()) {
                getArea()
            } else {
                showProvince(areaEntity)
            }
        }

        btn_change_address.setOnClickListener {


            var tenant = JSONObject()
            tenant["areaId"] = areaId
            tenant["address"] = et_address_info.text.toString()
            tenant["id"] = Api.getTenantId()

            var para = JSONObject()
            para["tenant"] = tenant
            submit(RequestJson.getRequestBody(para.toJSONString()))
        }
    }

    private fun submit(requestBody: RequestBody) {
        showLoading()
        val subscribe =
            RetrofitManager.service.submitTenantInfo(requestBody, Api.getTenantId()).compose(SchedulerUtils.ioToMain())
                .subscribe({
                    hideLoading()
                    if (it.resultCode == ErrorStatus.SUCCESS) {
                        ToastyUtils.showSuccess("修改成功")
                        finish()
                    } else {
                        showError(it.message!!)
                    }

                }, {
                    showError(ExceptionHandle.handleException(it))
                    hideLoading()
                })
        compositeDisposable.add(subscribe)
    }

    private fun showLoading() {
        CommonDialog.showLoading(mContext!!, Constant.Loading)
    }

    private fun hideLoading() {
        CommonDialog.cancle()
    }

    private fun showError(msg: String) {
        ToastyUtils.showError(msg)
    }

    private fun getArea() {
        showLoading()
        var subscribe = RetrofitManager.service.getAreaList().compose(SchedulerUtils.ioToMain())
            .subscribe({
                hideLoading()
                if (it.resultCode == ErrorStatus.SUCCESS) {
                    this.areaEntity = it.datas!!
                    showProvince(this.areaEntity)
                } else {
                    showError(it.message!!)
                }

            }, {
                showError(ExceptionHandle.handleException(it))
                hideLoading()
            })

        compositeDisposable.add(subscribe)
    }

    private fun showProvince(areaEntity: List<AreaEntity>) {
        var province = ArrayList<String>()

        for (areaEntity in areaEntity) {
            province.add(areaEntity.areaName)
        }
        val pvOptions = OptionsPickerBuilder(mContext!!,
            OnOptionsSelectListener { options1, options2, options3, v ->
                provinceName = province[options1]
                provinceId = areaEntity[options1].parentAreaId


                showCity(areaEntity[options1].listBaseArea)
            }
        ).setTitleText("选择省份").build<String>()
        pvOptions.setPicker(province)
        pvOptions.show()
    }

    private fun showCity(citys: List<BaseArea>) {
        var city = arrayListOf<String>()
        city.clear()
        for (baseArea in citys) {
            city.add(baseArea.areaName)
        }

        val pvOptions = OptionsPickerBuilder(mContext!!,
            OnOptionsSelectListener { options1, _, _, _ ->
                areaId = citys[options1].areaId
                areaName = city[options1]
                tv_tenant_address.text = provinceName + city[options1]

            }
        ).setTitleText("选择城市").build<String>()
        pvOptions.setPicker(city)
        pvOptions.show()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (compositeDisposable.isDisposed) compositeDisposable.clear()
    }

}
